package com.ty.tour.common.utils;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by liudiwen on 2018/7/16.
 */
public class StringUtil {
    private final static Logger logger = LoggerFactory.getLogger(StringUtil.class);

    public static List<Integer> string2List(String idStrs) {

        List<Integer> idList = new ArrayList<>();
        if (StringUtils.isEmpty(idStrs)) {
            logger.warn("string2List params is empty!");
            return idList;
        }

        List<String> ids = Arrays.asList(idStrs.split(","));
        for (String id : ids) {
            idList.add(Integer.valueOf(id.trim()));
        }
        return idList;
    }

    public static List<Integer> str2IntList(String idStrs) {

        List<Integer> idList = new ArrayList<>();
        if (StringUtils.isEmpty(idStrs)) {
            logger.warn("str2IntList params is empty!");
            return idList;
        }

        List<String> ids = Arrays.asList(idStrs.split(","));
        for (String id : ids) {
            idList.add(Integer.valueOf(id.trim()));
        }
        return idList;
    }

    //判断符号是否成对
    public static Boolean isCharDoubles(String str, char left, char right) {
        boolean bool = false;
        int top = 0;// 计数，左括号 1，右括号 -1，最后总和0则匹配
        boolean end = true;// true 表示匹配

        char[] isDouble = str.toCharArray();// 将字符串转化成字符数组

        // 遍历表达式中所有字符
        for (int i = 0; i < isDouble.length; i++) {
            // 如果是(则加1，进栈
            if (isDouble[i] == left) {
                top++;
            } else if (isDouble[i] == right) {// 如果是)则-1，出栈
                if (!(top == 0)) {
                    top--;
                } else {//top == 0,无左括号却有一个右括号，有一个右括号不匹配
                    end = false;
                    break;
                }
            }
        }

        // 循环结束时两种可能
        if (top == 0 && end) {
            bool = true;
        } else if (top != 0 && end) {
            bool = false;
        }
        return bool;
    }
    //判断字符串里面有没有中文
    public static boolean isContainChinese(String str) {

        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }

    /**
     * 去除字符串首尾两端指定的字符
     * */
    public static String trimBothEndsChars(String srcStr, char splitter,String splitter1) {
        Pattern pattern = Pattern.compile("^"+splitter+"|"+splitter1+"$");
        Matcher matcher = pattern.matcher(srcStr);
        return matcher.replaceAll("");
    }
}
